﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class report_ReadFolder : System.Web.UI.Page
{
    private Random random;
    private SqlConnection myConnection;
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            //Response.Write(connString);
            myConnection = new SqlConnection(connString);
            random = new Random((int)DateTime.Now.Ticks);
            ViewImportResult();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message + "<br /><br />" + ex.StackTrace);
        }
    }

    /// <summary>
    /// Tìm thư mục có chứa file ảnh để import vào table Patient
    /// </summary>
    /// <param name="folderPaths"></param>
    private void FindFolder(string folderPaths)
    {
        //======================================
        //Local code
        string fullPath = Directory.CreateDirectory(folderPaths).FullName;
        /*
        //======================================
        //Server code
        string fullPath = Path.Combine(Server.MapPath("/"), folderPaths);*/


        //Response.Write(string.Format("<br /> Find Folder {0} <br /><br />", folderPaths));
        string[] childfolderPaths = Directory.GetDirectories(fullPath);
        foreach (string localFolder in childfolderPaths)
        {
            string[] paths = localFolder.Split(new char[] { '\\' });
            string[] files = Directory.GetFiles(localFolder);
            //Response.Write(string.Format("<br /> File Count {0} <br /><br />", files.Length));
            if (files.Length > 1)
            {
                string folderPatient = folderPaths + "\\" + paths[paths.Length - 1];
                //Response.Write(string.Format("<br /> Patient Folder {0} <br /><br />", folderPatient));
                ImportData(folderPatient);
            }
            else
            {
                //Response.Write(string.Format("<br /> Local Folder {0} <br /><br />", folderPaths + "\\" + paths[paths.Length - 1]));
                FindFolder(folderPaths + "\\" + paths[paths.Length - 1]);
            }
        }
    }

    /// <summary>
    /// View dữ liệu trong table Patient
    /// </summary>
    private void ViewImportResult()
    {
        myConnection.Open();
        string sql = "SELECT * FROM Patient order by ID desc";

        SqlCommand myCommand = new SqlCommand(sql, myConnection);

        DataSet myDataSet = new DataSet();

        SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand);
        myAdapter.Fill(myDataSet);

        GridView1.DataSource = myDataSet;
        GridView1.DataBind();

        myConnection.Close();
    }

    /// <summary>
    /// Tạo random pass
    /// </summary>
    /// <param name="size"></param>
    /// <returns></returns>
    private string RandomString(int size)
    {
        StringBuilder builder = new StringBuilder();
        char ch;
        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
            builder.Append(ch);
        }
        return builder.ToString();
    }

    /// <summary>
    /// Import company
    /// </summary>
    /// <param name="companyName"></param>
    /// <param name="folderPath"></param>
    private int ImportCompany(string companyName, string folderPath)
    {
        string sql = "SELECT * FROM Company where FolderPath = '" + folderPath + "'";
        SqlCommand myCommand = new SqlCommand(sql, myConnection);
        SqlDataReader dr = myCommand.ExecuteReader();
        if (!dr.HasRows)
        {
            //Insert COMPANY
            string insertSql = string.Format("insert into Company (CompanyName, FolderPath, CreatedDate) values (N\'{0}\',N\'{1}\',N\'{2}\')", companyName, folderPath, DateTime.Now);
            myCommand = new SqlCommand(insertSql, myConnection);
            myCommand.ExecuteNonQuery();
        }
        dr.Close();
        int companyId = 0;
        myCommand = new SqlCommand(sql, myConnection);
        dr = myCommand.ExecuteReader();
        if (dr.HasRows)
        {
            dr.Read();
            companyId = (int)dr[0];
            dr.Close();
        }
        return companyId;
    }

    /// <summary>
    /// Import personal: bao gồm khách hàng cá nhân và khách hàng của cty
    /// </summary>
    /// <param name="code"></param>
    /// <param name="patientName"></param>
    /// <param name="folderPath"></param>
    private void ImportPersonal(string code, string patientName, int companyId, string folderPath)
    {
        string sql = "SELECT * FROM Patient where FolderPath = '" + folderPath + "'";
        SqlCommand myCommand = new SqlCommand(sql, myConnection);
        SqlDataReader dr = myCommand.ExecuteReader();
        if (!dr.HasRows)
        {
            dr.Close();
            string insertSql = "";
            if (companyId > 0)
                insertSql = string.Format("insert into Patient (Code, PatientName, CompanyID, Pass, FolderPath, CreatedDate) values (N\'{0}\',N\'{1}\',N\'{2}\',N\'{3}\',N\'{4}\',N\'{5}\')", code, patientName, companyId, RandomString(5), folderPath, DateTime.Now);
            else
                insertSql = string.Format("insert into Patient (Code, PatientName, Pass, FolderPath, CreatedDate) values (N\'{0}\',N\'{1}\',N\'{2}\',N\'{3}\',N\'{4}\')", code, patientName, RandomString(5), folderPath, DateTime.Now);
            myCommand = new SqlCommand(insertSql, myConnection);
            myCommand.ExecuteNonQuery();
        }
    }

    /// <summary>
    /// Import dữ liệu
    /// </summary>
    /// <param name="localFolder"></param>
    private void ImportData(string localFolder)
    {
        try
        {
            string[] paths = localFolder.Split(new char[] { '\\' });
            
            string codename = paths[paths.Length - 1];
            string[] names = codename.Split(new char[] { '-' });
            string code = names[0].Trim();
            //Response.Write(string.Format("<br /> Code {0} <br /><br />", code));
            string patientName = names[1].Trim();
            string companyName = paths[paths.Length - 2];

            string relativePath = String.Join("/", paths);
            //Response.Write(string.Format("<br /> Relative Path {0} <br /><br />", relativePath));
            
            //Kiểm tra tồn tại localFoder trong CSDL chưa
            //Response.Write(string.Format("<br /> Code {0} <br /><br />", code));
            myConnection.Open();
            int companyId = 0;
            //Kiểm tra xem đây có phải là COMPANY không
            if (companyName.ToLower() != "personal"){
                //Lấy folderPath của company
                string folderPath = localFolder.Substring(0, localFolder.IndexOf(codename)).Replace("\\", "/");
                companyId = ImportCompany(companyName, folderPath);
            }

            //Import personal
            ImportPersonal(code, patientName, companyId, relativePath);
            
            myConnection.Close();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        
    }

    protected void btnImportPatientData_Click(object sender, EventArgs e)
    {
        try
        {
            string rootFolder = "report\\results\\" + FolderLib.FileProcessing.CreateCurrentDateFolder();
            //string path = Directory.GetCurrentDirectory();
            
            //======================================
            //Local code
            string fullPath = Directory.CreateDirectory(rootFolder).FullName;
            /*
            //======================================
            //Server code
            string fullPath = Path.Combine(Server.MapPath("/"),rootFolder);*/
            
            //Response.Write(string.Format("<br /> Read {0} <br /><br />", fullPath));
            if (Directory.Exists(fullPath))
            {
                //Response.Write(string.Format("<br /> Exist {0} <br /><br />", fullPath));
                FindFolder(rootFolder);
                ViewImportResult();
            }
            else
                Response.Write(string.Format("Not exists {0} to read <br /><br />", rootFolder));
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message + "<br /><br />" + ex.StackTrace);
        }
    }
}
